package com.boolib;

import java.io.*;

public class SerializableUtil {


    public static byte[] serializable(Object obj){

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        try( ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {

            objectOutputStream.writeObject(obj);

            objectOutputStream.flush();

            byte[] bytes = byteArrayOutputStream.toByteArray();


            return bytes;

        } catch (IOException e) {
            e.printStackTrace();
        }


        return  null;



    }


    public static  Object deSerializable(byte[] bytes){

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);

        try (   ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)){

            Object object = objectInputStream.readObject();

            return object;

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return  null ;
    }
    public static void main(String[] args) {
        People people = new People(1,"s",true);

        byte[] bytes = SerializableUtil.serializable(people);



        People people1 = (People) SerializableUtil.deSerializable(bytes);


        String s = new String (bytes);

        System.out.println(s);
        System.out.println(people1);
    }




}

class People implements Serializable{


    private Integer id ;

    private String name;
    private boolean sex;

    public People(Integer id, String name, boolean sex) {
        this.id = id;
        this.name = name;
        this.sex = sex;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isSex() {
        return sex;
    }

    public void setSex(boolean sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "People{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex=" + sex +
                '}';
    }
}
